<template>
    <alertBox data-title="批量发薪" :isCloseType="true">
        <div class="process">
            <!-- ,{whichStep === 0 ? 'active' : '' , } -->
            <div :class="[whichStep === 0 ? 'active' : '', 'process-box']">
                <div class="no">
                    <i class="el-icon el-icon-check" />
                </div>
                <span>上传文件</span>
            </div>
            <div class="arrow">
                <i class="el-icon el-icon-arrow-right" />
            </div>
            <div :class="[whichStep === 1 ? 'active' : '', 'process-box']">
                <div class="no">
                    2
                </div>
                <span>确认信息</span>
            </div>
            <div class="arrow">
                <i class="el-icon el-icon-arrow-right" />
            </div>
            <div :class="[whichStep === 2 ? 'active' : '', 'process-box']">
                <div class="no">
                    3
                </div>
                <span>查看结果</span>
            </div>
        </div>

        <div class="box-block form" v-if="whichStep === 0">
            <el-upload
                class="upload-demo"
                :drag="!fileName"
                :disabled="!!fileName"
                :action="uploadAction"
                :headers="{ Authorization: 'Bearer' + ' ' + global.token }"
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                :on-success="fileSuccess"
                :on-error="fileEerror"
                :show-file-list="false"
                :data="{ checkWay: 'sync' }"
            >
                <div class="row">
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>发薪数据</span>
                        </div>
                        <div
                            class="value"
                            style="
                        display: flex;
                        align-items: center;
                        flex: auto;
                    "
                        >
                            <button class="btn import-btn">
                                <i class="el-icon el-icon-upload2" />导入
                            </button>
                            <div class="tipsText">
                                或拖拽至此处
                            </div>
                            <a
                                class="down-templete"
                                style="position: relative;z-index:10"
                                href="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/template/template-pay.xlsx"
                                @click.stop="
                                    () => {
                                        return;
                                    }
                                "
                                >模板下载</a
                            >
                            <!-- <button class="btn import-btn">
                                <i class="el-icon el-icon-upload2" />导入
                            </button>
                            <div class="tipsText">
                                或拖拽至此处
                            </div>
                            <a
                                class="down-templete"
                                style="position: relative;z-index:10"
                                href="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/template/template.xlsx"
                                @click.stop="
                                    () => {
                                        return
                                    }
                                "
                                >模板下载</a
                            > -->
                            <!-- [whichStep === 0 ? 'active' : '','process-box'] -->
                            <div :class="[fileName ? 'fileInfo' : '']">
                                {{ fileName ? "" + "文件名" : "" }}
                                <span style="color:#1989fa">
                                    {{ fileName }}
                                </span>
                                {{ fileSize ? "" + "文件大小" : "" }}
                                <span style="color:#1989fa">{{
                                    fileSize
                                }}</span>
                                <span
                                    :class="[fileName ? 'fileDel' : '']"
                                    @click.stop="onDeleteFile"
                                    >{{ fileName ? "×" : "" }}</span
                                >
                            </div>
                        </div>
                    </div>
                    <div></div>
                </div>
                <div class="row">
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>流程名称</span>
                        </div>
                        <div class="value">
                            <el-input
                                @click.stop="
                                    () => {
                                        return;
                                    }
                                "
                                placeholder="请输入流程名称"
                                name="processaName"
                                @input="onLoseBlur"
                                v-model="processaName"
                            />
                        </div>
                    </div>
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>派遣单位名称</span>
                        </div>
                        <div class="value">
                            <el-select
                                v-model="enterpriseIndex"
                                filterable
                                placeholder="请选择派遣单位"
                                @change="onEnterprise"
                            >
                                <el-option
                                    :disabled="
                                        item.isBlacklist || item.isForbidden
                                    "
                                    v-for="(item, index) in enterpriseList"
                                    :label="item.serveCompanyName"
                                    :value="index"
                                    :key="index"
                                    >{{ item.serveCompanyName }}</el-option
                                >
                            </el-select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>联系驻场</span>
                        </div>
                        <div class="value">
                            <el-select
                                @click.stop="
                                    () => {
                                        return;
                                    }
                                "
                                v-model="linkMan"
                                filterable
                                placeholder="请选择驻场"
                                @change="onLoseBlur"
                                @removeTag="onRemoveTag"
                                multiple
                            >
                                <el-option
                                    :label="item.userName"
                                    :value="item.userId"
                                    v-for="(item, index) in esidentList"
                                    v-bind:key="index"
                                    @click="residentDropdown(item.userName)"
                                    >{{
                                        item.userName + " " + item.phone
                                    }}</el-option
                                >
                            </el-select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>备注</span>
                        </div>
                        <div class="value">
                            <el-input
                                @click.stop="
                                    () => {
                                        return;
                                    }
                                "
                                placeholder="请输入备注信息"
                                @input="onLoseBlur"
                                :name="remarks"
                                v-model="remarks"
                            />
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>总金额</span>
                        </div>
                        <div class="value">
                            <el-input
                                placeholder="上传表单后自动填充"
                                disabled
                                name="totalAmount"
                                v-model="totalAmount"
                            />
                        </div>
                    </div>
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>总人数</span>
                        </div>
                        <div class="value">
                            <el-input
                                placeholder="上传表单后自动填充"
                                disabled
                                name="totalNumber"
                                v-model="totalNumber"
                            />
                        </div>
                    </div>
                </div>
                <el-button
                    class="btn mini-btn"
                    type="primary"
                    :disabled="isOnBtn"
                    @click.stop="onUploadFileNext"
                    >下一步</el-button
                >
            </el-upload>
        </div>
        <div class="form-error" v-if="errorList.length">
            <el-alert
                :title="
                    `本次上传文件共发现${errorList.length}处错误，请修改后重新上传`
                "
                type="error"
                center
                show-icon
            />
            <!-- <div class="operation-box">
                <div></div>
                <div class="align-items">
                    <button class="btn-red mini-btn ">删除</button>
                    <button class="mini-btn btn-white-blue btn-export-active">导出</button>
                </div>
            </div> -->
            <div class="error-table">
                <el-table :data="errorList">
                    <el-table-column
                        label="行号"
                        style="color:#F5F5F7"
                        :formatter="row => row.orderNum + 1"
                    />
                    <el-table-column
                        prop="userName"
                        style="color:#F5F5F7"
                        label="姓名"
                    />
                    <el-table-column
                        prop="idCard"
                        style="color:#F5F5F7"
                        label="身份证号"
                    />
                    <el-table-column
                        prop="detailRemarks"
                        style="color:#F5F5F7"
                        label="备注"
                    />
                    <el-table-column
                        prop="errorMsg"
                        style="color:#F5F5F7"
                        label="错误信息"
                    />
                </el-table>
            </div>
        </div>

        <!-- 确认发薪 -->
        <div class="box-block enclosure" v-if="whichStep === 1">
            <div class="form-left">
                <div class="info-title">
                    发薪数据单
                </div>
                <el-scrollbar max-height="430px">
                    <!-- <img src="@/assets/xlsx/xlsx-template.png" class="xlsx-img"/> -->
                    <el-table
                        :data="fileContentList"
                        :row-class-name="tableRowClassName"
                        style="width: 100%"
                        :header-row-style="{ color: '#202536' }"
                        :row-style="{ color: '#5E617D' }"
                        :cell-style="{
                            height: '35px',
                            padding: '0'
                        }"
                    >
                        <el-table-column type="index" label="序号" width="50" />
                        <el-table-column
                            prop="userName"
                            width="80"
                            label="姓名"
                        />
                        <el-table-column
                            prop="idCard"
                            label="身份证号"
                            width="170"
                        />
                        <el-table-column prop="totalMoney" label="薪资">
                            <template #default="scope">
                                <p v-if="editId !== scope.row.id">
                                    {{ scope.row.totalMoney }}
                                </p>
                                <p v-else>
                                    <el-input
                                        placeholder="薪资"
                                        v-model="scope.row.totalMoney"
                                    />
                                </p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="totalMoney" label="备注">
                            <template #default="scope">
                                <p v-if="editId !== scope.row.id">
                                    {{ scope.row.detailRemarks }}
                                </p>
                                <p v-else>
                                    <el-input
                                        maxlength="20"
                                        placeholder="备注"
                                        v-model="scope.row.detailRemarks"
                                    />
                                </p>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="50">
                            <template #default="scope">
                                <p
                                    class="link"
                                    @click="onFileEdit(scope.row.id)"
                                >
                                    {{
                                        editId === scope.row.id
                                            ? "保存"
                                            : "编辑"
                                    }}
                                </p>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-scrollbar>
                <el-pagination
                    class="pagination"
                    layout="prev, pager, next"
                    @current-change="handleCurrentChange"
                    :page-size="100"
                    :total="userList.length"
                ></el-pagination>
            </div>
            <div class="form-right">
                <div class="info-title">
                    确认信息
                </div>
                <div class="info-enclosure-name parallel">
                    <div class="info-left">
                        附件名称：
                    </div>
                    <div class="info-right">
                        {{ fileName }}
                    </div>
                </div>
                <div class="info-name parallel">
                    <div class="info-left">
                        流程名称：
                    </div>
                    <div class="info-right">
                        {{ processaName }}
                    </div>
                </div>
                <div class="info-month parallel">
                    <div class="info-left">
                        备注：
                    </div>
                    <div class="info-right">
                        {{ remarks }}
                    </div>
                </div>
                <div class="info-pay-enterprise parallel ">
                    <div class="info-left">
                        派遣单位：
                    </div>
                    <div class="info-right">
                        {{ enterpriseName }}
                    </div>
                </div>
                <div class="parallel">
                    <div class="info-left">
                        联系驻厂：
                    </div>
                    <div class="info-right">
                        <span
                            v-for="(item, index) in contactResident"
                            v-bind:key="index"
                            >{{ item + " " }}
                        </span>
                    </div>
                </div>
                <div class="info-people-num parallel">
                    <div class="info-left">
                        总人数：
                    </div>
                    <div class="info-right">{{ totalNumber }}人</div>
                </div>
                <div class="info-total-money parallel">
                    <div class="info-left">
                        总金额：
                    </div>
                    <div class="info-right info-right-num">
                        ￥{{ totalAmount }}
                    </div>
                </div>
                <div class="parallel" style="justify-content: space-between">
                    <button class="btn-white" @click="whichStep -= 1">
                        重新选择
                    </button>
                    <button class="btn" @click="onAddBatchPay">确认添加</button>
                </div>
            </div>
        </div>
        <div class="box-block result" v-if="whichStep === 2">
            <img
                src="@/assets/xlsx/success.png"
                alt=""
                class="result-success"
            />
            <div class="result-title">
                提交审核成功
            </div>
            <!-- <div class="result-name">
                预计两小时内到账
            </div> -->
            <button class="btn" @click="onCloseEject">返回列表</button>
            <div class="result-info">
                <div class="info-enclosure-name parallel">
                    <div class="info-left">
                        附件名称：
                    </div>
                    <div class="info-right">
                        {{ fileName }}
                    </div>
                </div>
                <div class="info-name parallel">
                    <div class="info-left">
                        流程名称：
                    </div>
                    <div class="info-right">
                        {{ processaName }}
                    </div>
                </div>
                <div class="info-month parallel">
                    <div class="info-left">
                        备注：
                    </div>
                    <div class="info-right">
                        {{ remarks }}
                    </div>
                </div>
                <div class="info-pay-enterprise parallel ">
                    <div class="info-left">
                        发薪派遣单位：
                    </div>
                    <div class="info-right">
                        {{ enterpriseName }}
                    </div>
                </div>
                <div class="parallel">
                    <div class="info-left">
                        联系驻厂：
                    </div>
                    <div class="info-right">
                        <span
                            v-for="(item, index) in contactResident"
                            v-bind:key="index"
                            >{{ item + " " }}
                        </span>
                    </div>
                </div>
                <div class="info-people-num parallel">
                    <div class="info-left">
                        总人数：
                    </div>
                    <div class="info-right">{{ totalNumber }}人</div>
                </div>
                <div class="info-total-money parallel">
                    <div class="info-left">
                        总金额：
                    </div>
                    <div class="info-right info-right-num">
                        ￥{{ totalAmount }}
                    </div>
                </div>
            </div>
        </div>
    </alertBox>
</template>

<script lang="ts" setup>
import alertBox from './alert-box.vue'
</script>
<script lang="ts">
import { defineComponent } from 'vue'
import {
    getEnterpriseNameList,
    EnterpriseDto,
    getResidentNameList
} from '@/api/enterprise'
import global from '@/utils/global'
import { postBatchPay } from '@/api/pay'
import { ElScrollbar } from 'element-plus'
import { formTesting } from '@/utils/util'
export default defineComponent({
    created() {
        this.getEnterpriseNameList()
        this.getResidentNameList()
    },
    data() {
        return {
            uploadAction:
                process.env.VUE_APP_BASE_URL +
                '/rest/pay/processOrder/importDataByIdCard', // 导入的路径
            whichStep: 0,
            processaName: '', // 流程名称
            enterpriseIndex: '' as string | number, // 派遣单位名称
            enterpriseName: '', // 派遣单位名称
            enterpriseId: '', // 派遣单位Id
            contactResident: [] as string[], // 联系驻场
            linkMan: [] as string[],
            remarks: '', // 备注
            totalNumber: '', // 总人数
            totalAmount: '' as number | string, // 总金额
            enterpriseList: [] as any, // 派遣单位列表
            esidentList: [] as {
                userName: string;
                userId: string;
                phone: string;
            }[], // 驻场列表
            errorList: [] as {
                idCard: string;
                orderNum: number;
                userName: string;
            }[], // 错误数据列表
            flowCode: '',
            fileName: '' as string,
            userList: [] as {
                id?: number | string;
                idCard: string;
                totalMoney: number | string;
                userName: string;
            }[],
            userListTotal: 0,
            isOnBtn: true,
            fileSize: '',
            dom: '',
            pageNum: 1,
            pageSize: 100,
            fileContentList: [] as {
                id?: number | string;
                idCard: string;
                isError?: boolean;
                totalMoney: number | string;
                userName: string;
            }[],
            editId: '',
            userIndex: 0
        }
    },
    methods: {
        tableRowClassName(row: { row: { isError: boolean } }) {
            console.log(row.row.isError)
            if (row.row.isError) {
                return 'warm-row'
            }
            return ''
        },
        // 上传文件编辑
        onFileEdit(event: string) {
            if (this.editId !== '' && this.editId !== event) {
                this.$message.error('请先保存')
                return
            }
            if (this.editId === event) {
                this.editId = ''
                const userInfo = this.fileContentList.filter(
                    (item: { id?: number | string }) => item.id === event
                )
                this.userList.forEach((item, index) => {
                    // 拿到修改
                    if (item.idCard === userInfo[0].idCard) {
                        this.userIndex = index
                    }
                })
                // 赋值到主列表
                this.userList[this.userIndex].userName = userInfo[0].userName
                this.userList[this.userIndex].idCard = userInfo[0].idCard
                this.userList[this.userIndex].totalMoney =
                    userInfo[0].totalMoney
                // this.totalAmount
                this.totalAmount = 0
                this.userList.forEach(item => {
                    // 总金额重新计算
                    (this.totalAmount as number) += Number(item.totalMoney)
                })
            } else {
                this.editId = event
            }
        },
        handleCurrentChange(event: number) {
            this.pageNum = event
            this.fileContentList = this.userList.slice(
                (this.pageNum - 1) * 100,
                this.pageNum * 100
            )
            console.log(this.fileContentList, 'fileContentList')
        },
        // 查询公司下派遣单位列表
        async getEnterpriseNameList() {
            const result = await getEnterpriseNameList()
            this.enterpriseList = result.list
        },
        async getResidentNameList() {
            const result = await getResidentNameList()
            this.esidentList = result
        },
        onEnterprise(e: number) {
            let obj = this.enterpriseList[e]
            if (obj.isBlacklist || obj.isForbidden) {
                this.enterpriseIndex = ''
            } else {
                this.enterpriseId = this.enterpriseList[
                    this.enterpriseIndex as number
                ].id
                this.enterpriseName = this.enterpriseList[
                    this.enterpriseIndex as number
                ].serveCompanyName
                console.log('enterpriseId', this.enterpriseId)
                this.onLoseBlur()
            }
        },
        residentDropdown(name: string) {
            console.log(name, 'name')
            const index = this.contactResident.indexOf(name)
            console.log(index, 'index')
            if (index === -1) {
                this.contactResident.push(name)
            } else {
                this.contactResident.splice(index, 1)
            }
            console.log(index, 'index')
            console.log(this.contactResident, 'contactResident')
        },
        onUploadFileNext() {
            if (/\s+/.test(this.processaName)) {
                this.$message.warning('流程名称不可输入多个空格')
                return
            }
            if (!this.processaName) {
                this.$message.warning('请输入流程名称')
                return
            }
            if (!this.remarks) {
                this.$message.warning('请输入备注')
                return
            }
            if (!this.enterpriseName) {
                this.$message.warning('请选择派遣单位名称')
                return
            }
            if (this.contactResident.length === 0) {
                this.$message.warning('请选择驻场')
                return
            }
            if (!this.totalNumber) {
                this.$message.warning('请导入文件')
                return
            }
            console.log(this.contactResident, 'contactResident')
            this.whichStep = 1
        },
        fileSuccess(
            response: {
                code: number;
                msg: string;
                data: {
                    flowCode: string;
                    totalMoney: number;
                    totalPerson: string;
                    userList: {
                        id?: number;
                        idCard: string;
                        isError?: boolean;
                        totalMoney: number | string;
                        userName: string;
                    }[];
                    errorUserList: {
                        idCard: string;
                        orderNum: number;
                        userName: string;
                    }[];
                };
            },
            file: { raw: { name: string; size: string } }
        ) {
            if (response.code === 500) {
                this.$message.error(response.msg)
                return
            }
            this.fileSize = (Number(file.raw.size) / 1024).toFixed(1) + 'kb'
            this.fileName = file.raw.name
            this.flowCode = response.data.flowCode
            this.totalAmount = response.data.totalMoney
            this.totalNumber = response.data.totalPerson
            // userList加字段
            // 数据分割
            this.fileContentList = response.data.userList.slice(0, 100)
            this.errorList = response.data.errorUserList
            console.log(this.fileContentList, 'fileContentList')
            response.data.userList.forEach((item, index) => {
                item.id = index
            })
            this.userList = response.data.userList
            this.userListTotal = response.data.userList.length / 100
            this.$message.success('上传成功')
            this.onLoseBlur()
        },
        fileEerror() {
            this.$message.error('文件上传失败')
        },
        async onAddBatchPay() {
            await postBatchPay({
                flowCode: this.flowCode,
                linkman: this.linkMan,
                projectName: this.processaName,
                remarks: this.remarks,
                serveCompanyId: this.enterpriseId,
                serveCompanyName: this.enterpriseName,
                totalMoney: this.totalAmount as number,
                totalPerson: this.totalNumber,
                userList: this.userList
            })
            this.whichStep += 1
        },
        onCloseEject() {
            this.$emit('close')
            this.$emit('complete')
        },
        onLoseBlur() {
            if (
                this.processaName &&
                this.enterpriseName &&
                this.remarks &&
                this.contactResident &&
                this.totalNumber &&
                !this.errorList.length
            ) {
                this.isOnBtn = false
            } else {
                this.isOnBtn = true
            }
        },
        onRemoveTag(event: any) {
            const index = this.contactResident.indexOf(
                this.esidentList.filter(item => item.userId === event)[0]
                    .userName
            )
            this.contactResident.splice(index, 1)
            console.log(index, 'index')
            console.log(event, 'event')
        },
        onDeleteFile() {
            this.totalAmount = 0
            this.totalNumber = ''
            this.fileSize = ''
            this.fileName = ''
            this.$message.success('删除成功')
        }
    }
})
</script>

<style scoped lang="stylus">
// 弹窗样式
eject()
ejectFrom()
:deep() .container-c
    width 1060px
.process
    width 950px
.box-block
    width 950px
.value
    width 240px !important
.el-input--prefix .el-input__inner
    width 240px !important
:deep() .el-upload-dragger
    width 100%
    height 100%
    border-color transparent
:deep().el-upload.el-upload--text
    width 100%
.tipsText
    margin-left 10px
.mini-btn
    margin 0 auto
    width 100px
.fileInfo
    margin-left 20px
    border 1px solid #f4f4f5
    padding 2px 7px
    border-radius 13px
    display flex
    align-items center
    background #f4f4f5
    .fileDel
        border-radius 44px
        border 2px solid #ccc
        width 15px
        height 15px
        line-height 15px
        text-align center
        display block
        color #ccc
        margin-left 5px
.form-left
    flex 1
    margin-right 20px
    height 312px
/deep/.el-table--scrollable-y .el-table__body-wrapper {
   overflow-y clip
}
// .el-table td.el-table__cell div
//     white-space pre-wrap
// .table-column-alone
//     width 100px
.el-scrollbar__wrap
    overflow auto
    height 100%
.el-pagination{
    float right
}
.el-table>>>.warm-row {
  background #fdf6ec
  color white
}

.form-error {
    background-color: #F5F5F7;
    .error-table{
        padding: 16px 24px;
    }
}
.operation-box
    width 100%
    display flex
    align-items center
    justify-content space-between
    padding 0 24px
    padding-top 10px
.btn-export-active
    margin-left 10px
</style>
